﻿using System.Threading;
using ConsoleDemo.Data;
using TradeHelp.MaterializedObjectViews;
using TradeHelp.Utilities;

namespace ConsoleDemo
{
    public static class DataSource
    {
        private static readonly string[] _names = new[] { "Sayre", "Hayden", "Dana", "Brit", "Marla", "Ronald" };
        private static readonly string[] _occupations = new[] { "Engineer", "Artist", "Web Designer", "Nurse", "Teacher" };
        private static readonly string[] _brands = new[] { "Nike", "Puma", "Ugz", "Reebok" };
        private static readonly int[] _sizes = new[] { 10, 11, 12 };
        private static readonly TableView<Person> Family = new TableView<Person>();
        private static readonly TableView<Shoe> Shoes = new TableView<Shoe>();
        private static readonly Thread _familyThread;
        private static readonly Thread _shoesThread;
        private static volatile bool _stop;

        static DataSource()
        {
            _familyThread = new Thread(() =>
            {
                while (!_stop)
                {
                    Family.Process(GetPersonMsg());
                    Thread.Sleep(500);
                }
            });

            _shoesThread = new Thread(() =>
            {
                while (!_stop)
                {
                    Shoes.Process(GetShoeMsg());
                    Thread.Sleep(250);
                }
            });
        }

        public static void StartStreaming()
        {
            _familyThread.Start();
            _shoesThread.Start();
        }

        public static void Stop()
        {
            _stop = true;
        }

        public static View<Person> FamilyView
        {
            get { return Family; }
        }

        public static View<Shoe> ShoeView
        {
            get { return Shoes; }
        }

        private static ViewMessage<Person> GetPersonMsg()
        {
            var name = _names.GetRandom();
            var age = RandomHelper.GetRandom(20, 70);
            var occupation = _occupations.GetRandom();
            var person = new Person(name, age, occupation);

            if (RandomHelper.GetRandom(7) == 0)
            {
                return ViewMessage<Person>.CreateRemove(person);
            }
            return ViewMessage<Person>.CreateAdd(person);
        }

        private static ViewMessage<Shoe> GetShoeMsg()
        {
            var name = _names.GetRandom();
            var brand = _brands.GetRandom();
            var size = _sizes.GetRandom();
            var shoe = new Shoe(name, brand, size);

            if (RandomHelper.GetRandom(7) == 0)
            {
                return ViewMessage<Shoe>.CreateRemove(shoe);
            }
            return ViewMessage<Shoe>.CreateAdd(shoe);
        }
    }
}